package org.dxy.trigger.http.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.api.dto.request.factory.CreateFactoryRequest;
import org.dxy.api.dto.request.factory.UpdateFactoryRequest;
import org.dxy.api.response.R;
import org.dxy.infrastructure.entity.query.FactoryViewEntity;
import org.dxy.infrastructure.persistent.service.FactoryViewService;
import org.dxy.infrastructure.persistent.service.WorkshopViewService;
import org.dxy.infrastructure.util.UserContext;
import org.dxy.trigger.http.service.FactoryApplicationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 工厂应用服务实现类
 * @author dxy
 * @createTime 2025/8/18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FactoryApplicationServiceImpl implements FactoryApplicationService {
    
    private final FactoryViewService factoryViewService;
    private final WorkshopViewService workshopViewService;

    @Transactional
    @Override
    public R<Long> create(CreateFactoryRequest request) {
        try {
            log.info("开始创建工厂: factoryCode={}, factoryName={}", request.getFactoryCode(), request.getFactoryName());
            
            // 检查工厂编码是否已存在
            if (factoryViewService.existsByFactoryCode(request.getFactoryCode())) {
                return R.fail("工厂编码已存在");
            }
            
            // 创建工厂实体
            FactoryViewEntity factory = FactoryViewEntity.builder()
                    .factoryCode(request.getFactoryCode())
                    .factoryName(request.getFactoryName())
                    .address(request.getAddress())
                    .phone(request.getPhone())
                    .manager(request.getManager())
                    .status("ACTIVE")
                    .description(request.getDescription())
                    .createdBy(UserContext.getCurrentUser())
                    .createdTime(LocalDateTime.now())
                    .updatedBy(UserContext.getCurrentUser())
                    .updatedTime(LocalDateTime.now())
                    .deleted(0)
                    .build();
            
            factoryViewService.save(factory);
            
            log.info("工厂创建成功: factoryId={}", factory.getId());
            return R.ok(factory.getId(), "工厂创建成功");
            
        } catch (Exception e) {
            log.error("创建工厂失败", e);
            return R.fail("创建工厂失败: " + e.getMessage());
        }
    }

    @Transactional
    @Override
    public R<Void> update(Long factoryId, UpdateFactoryRequest request) {
        try {
            log.info("开始更新工厂: factoryId={}", factoryId);
            
            FactoryViewEntity factory = factoryViewService.getById(factoryId);
            if (factory == null) {
                return R.fail("工厂不存在");
            }
            
            // 更新工厂信息
            factory.setFactoryName(request.getFactoryName());
            factory.setAddress(request.getAddress());
            factory.setPhone(request.getPhone());
            factory.setManager(request.getManager());
            factory.setDescription(request.getDescription());
            factory.setUpdatedBy(UserContext.getCurrentUser());
            factory.setUpdatedTime(LocalDateTime.now());
            
            factoryViewService.updateById(factory);
            
            log.info("工厂更新成功: factoryId={}", factoryId);
            return R.ok("工厂更新成功");
            
        } catch (Exception e) {
            log.error("更新工厂失败, factoryId={}", factoryId, e);
            return R.fail("更新工厂失败: " + e.getMessage());
        }
    }

    @Transactional
    @Override
    public R<Void> enable(Long factoryId) {
        try {
            log.info("开始启用工厂: factoryId={}", factoryId);
            
            FactoryViewEntity factory = factoryViewService.getById(factoryId);
            if (factory == null) {
                return R.fail("工厂不存在");
            }
            
            if ("ACTIVE".equals(factory.getStatus())) {
                return R.fail("工厂已经是启用状态");
            }
            
            factory.setStatus("ACTIVE");
            factory.setUpdatedBy(UserContext.getCurrentUser());
            factory.setUpdatedTime(LocalDateTime.now());
            
            factoryViewService.updateById(factory);
            
            log.info("工厂启用成功: factoryId={}", factoryId);
            return R.ok("工厂启用成功");
            
        } catch (Exception e) {
            log.error("启用工厂失败, factoryId={}", factoryId, e);
            return R.fail("启用工厂失败: " + e.getMessage());
        }
    }

    @Transactional
    @Override
    public R<Void> disable(Long factoryId) {
        try {
            log.info("开始禁用工厂: factoryId={}", factoryId);
            
            FactoryViewEntity factory = factoryViewService.getById(factoryId);
            if (factory == null) {
                return R.fail("工厂不存在");
            }
            
            if ("INACTIVE".equals(factory.getStatus())) {
                return R.fail("工厂已经是禁用状态");
            }
            
            factory.setStatus("INACTIVE");
            factory.setUpdatedBy(UserContext.getCurrentUser());
            factory.setUpdatedTime(LocalDateTime.now());
            
            factoryViewService.updateById(factory);
            
            log.info("工厂禁用成功: factoryId={}", factoryId);
            return R.ok("工厂禁用成功");
            
        } catch (Exception e) {
            log.error("禁用工厂失败, factoryId={}", factoryId, e);
            return R.fail("禁用工厂失败: " + e.getMessage());
        }
    }

    @Transactional
    @Override
    public R<Void> delete(Long factoryId) {
        try {
            log.info("开始删除工厂: factoryId={}", factoryId);
            
            FactoryViewEntity factory = factoryViewService.getById(factoryId);
            if (factory == null) {
                return R.fail("工厂不存在");
            }
            
            // 检查是否有关联的车间
            long workshopCount = workshopViewService.countByFactoryId(factoryId);
            if (workshopCount > 0) {
                return R.fail("工厂下还有车间，不能删除");
            }
            
            factoryViewService.removeById(factoryId);
            
            log.info("工厂删除成功: factoryId={}", factoryId);
            return R.ok("工厂删除成功");
            
        } catch (Exception e) {
            log.error("删除工厂失败, factoryId={}", factoryId, e);
            return R.fail("删除工厂失败: " + e.getMessage());
        }
    }

    @Override
    public R<Page<FactoryViewEntity>> page(Page<FactoryViewEntity> page, FactoryViewEntity query) {
        try {
            LambdaQueryWrapper<FactoryViewEntity> queryWrapper = new LambdaQueryWrapper<>();
            
            if (query != null) {
                if (query.getFactoryCode() != null && !query.getFactoryCode().isEmpty()) {
                    queryWrapper.like(FactoryViewEntity::getFactoryCode, query.getFactoryCode());
                }
                if (query.getFactoryName() != null && !query.getFactoryName().isEmpty()) {
                    queryWrapper.like(FactoryViewEntity::getFactoryName, query.getFactoryName());
                }
                if (query.getStatus() != null && !query.getStatus().isEmpty()) {
                    queryWrapper.eq(FactoryViewEntity::getStatus, query.getStatus());
                }
                if (query.getManager() != null && !query.getManager().isEmpty()) {
                    queryWrapper.like(FactoryViewEntity::getManager, query.getManager());
                }
            }
            
            queryWrapper.orderByDesc(FactoryViewEntity::getCreatedTime);
            
            Page<FactoryViewEntity> result = factoryViewService.page(page, queryWrapper);
            return R.ok(result, "查询成功");
            
        } catch (Exception e) {
            log.error("查询工厂列表失败", e);
            return R.fail("查询工厂列表失败: " + e.getMessage());
        }
    }

    @Override
    public R<FactoryViewEntity> getById(Long factoryId) {
        try {
            FactoryViewEntity factory = factoryViewService.getById(factoryId);
            if (factory != null) {
                return R.ok(factory, "查询成功");
            } else {
                return R.fail("工厂不存在");
            }
        } catch (Exception e) {
            log.error("查询工厂详情失败, factoryId={}", factoryId, e);
            return R.fail("查询工厂详情失败: " + e.getMessage());
        }
    }

    @Override
    public R<Page<FactoryViewEntity>> getByStatus(Page<FactoryViewEntity> page, String status) {
        try {
            LambdaQueryWrapper<FactoryViewEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FactoryViewEntity::getStatus, status);
            queryWrapper.orderByDesc(FactoryViewEntity::getCreatedTime);
            
            Page<FactoryViewEntity> result = factoryViewService.page(page, queryWrapper);
            return R.ok(result, "查询成功");
            
        } catch (Exception e) {
            log.error("根据状态查询工厂列表失败, status={}", status, e);
            return R.fail("根据状态查询工厂列表失败: " + e.getMessage());
        }
    }

    @Override
    public R<List<FactoryViewEntity>> getEnabledFactories() {
        LambdaQueryWrapper<FactoryViewEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FactoryViewEntity::getStatus, "enable");
        queryWrapper.orderByAsc(FactoryViewEntity::getId);
        List<FactoryViewEntity> result = factoryViewService.list(queryWrapper);
        return R.ok(result, "查询成功");
    }
}